package context;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.yaml.snakeyaml.Yaml;

import com.alibaba.fastjson.JSON;

import config.mm_config;
import core.reactor.mm_reactor;
import core.reactor.mm_start;
import log.mm_logger;
import utils.mm_thread;

/**
 * 配置文件守护，发现配置文件更改。在稍后将会更新内存中的配置文件
 * @author dongyazhuo
 */
public class mm_config_guard implements Runnable {

	private String TAG = mm_config_guard.class.getSimpleName() + " ";

	private String path;

	private Yaml yaml = new Yaml();

	public Map<String, String> exclude = new HashMap<>();

	public mm_config_guard(String path) {
		super();
		this.path = path;
	}

	@Override
	public void run() {
		action();
	}

	private void action() {
		while (true) {
			mm_thread.sleep(5000L);
			try {
				query_or_update();
			} catch (Exception e) {
				mm_logger.w(TAG + " config file error ,please check!!! " + e);
			}
			mm_logger.i(TAG + " check config update ...");
		}
	}

	private void query_or_update() throws IOException {
		mm_context _mm_context = mm_context.instance();
		File[] tempList = new File(path).listFiles();
		for (int i = 0; i < tempList.length; i++) {
			if (tempList[i].isFile()) {
				String resource = path + "\\" + tempList[i].getName();
				InputStream stream = new FileInputStream(new File(resource));
				mm_config _new_config = yaml.loadAs(stream, mm_config.class);
				_new_config.setUrl_config(get_url_config());
				mm_config _mm_config = _mm_context.get_configs().get(resource);
				// 新创建的配置文件及原配置未启动更新为启动状态的,启动一个新的反应器
				String user_name = _new_config.getSet().getAccount_12306().getUser();
				if (null == _mm_config && null == exclude.get(user_name)) {
					// 启动一个反应器
					_new_config.setUrl_config(get_url_config());
					mm_start.instance().start(_new_config);
					_mm_context.set_configs(resource, _new_config);
				}
				// 变更了配置文件
				if (!JSON.toJSONString(_new_config).equals(JSON.toJSONString(_mm_config))) {
					mm_start.instance();
					// 关闭反应器
					mm_reactor _mm_reactor = mm_start.mm_reactor_group.get(_mm_config);
					new mm_thread().start(new Runnable() {

						@Override
						public void run() {
							mm_start.stop(_mm_reactor);
						}
					});
					mm_thread.sleep(2000L);
					// 启动一组新的反应器
					_new_config.setUrl_config(get_url_config());
					mm_start.instance().start(_new_config);
					_mm_context.set_configs(resource, _new_config);
				}
				stream.close();
			}
		}
	}

	private LinkedHashMap<String, Map<String, Object>> get_url_config() {
		// 如果读入Map,这里可以是Mapj接口,默认实现为LinkedHashMap
		InputStream inputStream = mm_config.class.getResourceAsStream("/url_config.yml");
		LinkedHashMap<String, Map<String, Object>> url_config = yaml.loadAs(inputStream, LinkedHashMap.class);
		return url_config;
	}

}
